/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EntityEdit.java
 *
 * Created on 11-jul-2011, 17:51:39
 */
package pfc.gui;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.MutableComboBoxModel;
import javax.swing.table.DefaultTableModel;
import org.apache.commons.lang.StringUtils;
import pfc.arbol.EntityTreeNode;
import pfc.comun.IDEpfc;
import pfc.interfaces.Salvable;
import pfc.modeloer.ERAttrib;
import pfc.modeloer.ERElement.EntityType;
import pfc.modeloer.ERModel;
import pfc.modeloer.ERRelationShip;
import pfc.modeloer.EREntity;
import pfc.modeloer.ERModelIO;
import pfc.modeloer.ManyToManyRelationShip;
import pfc.modeloer.OneToManyRelationShip;
import pfc.modeloer.ERReference;

/**
 *
 * @author xandru
 */
public class EntityEdit extends Editor implements Salvable {

    EntityTreeNode _nodo;
    EREntity _e;

    /** Creates new form EntityEdit */
    public EntityEdit(EntityTreeNode nodo) {
        this._nodo = nodo;
        _e = nodo.getEntity();
        initComponents();
        loadComboBox();
        loadRelationShipData();
        loadAtributesData();
        loadGeneracionIdentidades();
    }

    /*
    public EntityEdit(EREntity e) {
        _e = e;
        initComponents();
        loadRelationShipData();
        loadAtributesData();
    }
*/
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tRelaciones = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        attDisponibles = new javax.swing.JList();
        jScrollPane3 = new javax.swing.JScrollPane();
        attSelected = new javax.swing.JList();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        comboTipo = new javax.swing.JComboBox();
        jCheckBox1 = new javax.swing.JCheckBox();

        jButton1.setText("Guardar");
        jButton1.setEnabled(false);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cerrar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText("Atributos representativos");
        jLabel1.setToolTipText("Atributos descriptivos de la entidad que se muestran en las relaciones");

        tRelaciones.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Relacionada Con", "Nombre Relacion", "Tipo Relacion", "Atributo", "Atributo Relacionado"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tRelaciones);

        jLabel2.setText("Relaciones en la que participa la entidad");

        jLabel3.setText("Disponibles");

        jLabel4.setText("Seleccionados");

        attDisponibles.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        attDisponibles.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(attDisponibles);

        attSelected.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        attSelected.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane3.setViewportView(attSelected);

        jButton5.setText(">");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton6.setText("<");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jLabel5.setText("Tipo de Entidad:");

        comboTipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboTipoActionPerformed(evt);
            }
        });

        jCheckBox1.setText("Generar Identidad (Clave Primaria) automaticamente");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(157, 157, 157)
                                .addComponent(jButton1)
                                .addGap(18, 18, 18)
                                .addComponent(jButton2))
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel3)
                                            .addComponent(jLabel1)
                                            .addComponent(jCheckBox1)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(jLabel5)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(comboTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                        .addGap(122, 122, 122)
                                        .addComponent(jLabel4))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jButton6)
                                            .addComponent(jButton5))
                                        .addGap(18, 18, 18)
                                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                        .addContainerGap(110, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(comboTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jCheckBox1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(41, 41, 41)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGap(30, 30, 30)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton6)
                        .addGap(11, 11, 11)))
                .addGap(52, 52, 52)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.setVisible(false);
        this.getParent().remove(this);
        IDEpfc.app.getIDE().removeChanged(this);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        DefaultListModel listaDisponibles =  (DefaultListModel) attDisponibles.getModel();
        DefaultListModel listaSeleccionados = (DefaultListModel) attSelected.getModel();

        for(Enumeration e=listaSeleccionados.elements();e.hasMoreElements();)
        {
            String att = (String)e.nextElement();
            this._e.addRepresentativeAttribute(att);
        }

        System.out.println("Guardando configuracion Entidad");
        save();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed

        // TODO add your handling code here:
        DefaultListModel listaDisponibles =  (DefaultListModel) attDisponibles.getModel();
        DefaultListModel listaSeleccionados = (DefaultListModel) attSelected.getModel();
        int aPasar = attDisponibles.getSelectedIndex();
        if (aPasar > -1)
        {
           listaSeleccionados.addElement(listaDisponibles.elementAt(aPasar));
           listaDisponibles.removeElementAt(aPasar);
           jButton1.setEnabled(true);
        }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        // TODO add your handling code here:
        DefaultListModel listaDisponibles =  (DefaultListModel) attDisponibles.getModel();
        DefaultListModel listaSeleccionados = (DefaultListModel) attSelected.getModel();
        int aPasar = attSelected.getSelectedIndex();
        if (aPasar > -1)
        {
            listaDisponibles.addElement(listaSeleccionados.elementAt(aPasar));
           listaSeleccionados.removeElementAt(aPasar);
           jButton1.setEnabled(true);
        }
    }//GEN-LAST:event_jButton6ActionPerformed

    private void comboTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboTipoActionPerformed
        jButton1.setEnabled(true);
    }//GEN-LAST:event_comboTipoActionPerformed

    public void save() {
        //System.out.println("Tipo de entidad ->" + comboTipo.getSelectedItem());
        this._e.setErElementType(EntityType.valueOf((String) comboTipo.getSelectedItem()));
        this._e.setGenerateIdentity(this.jCheckBox1.isSelected());
        ERModel m = this._e.getErModel();
        String fichero = this._nodo.getERModelFile();
        try {
            new ERModelIO().doERModel2XML(m, fichero);
            IDEpfc.logTime("Datos de entidad " + _e.getName() + " guardados");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(EntityEdit.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList attDisponibles;
    private javax.swing.JList attSelected;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox comboTipo;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable tRelaciones;
    // End of variables declaration//GEN-END:variables

    private void loadRelationShipData() {
        ERModel erModel = this._e.getErModel();
        DefaultTableModel m = (DefaultTableModel) tRelaciones.getModel();
        
//        System.out.println("Relaciones de la entidad " + _e.getName());
        for (ERRelationShip r : _e.getRelationShipList()) {
            String relacionadaCon;
            String nombreRelacion = r.getName();
            String tipoRelacion = r.getType();
            String atributoLocal = "-";
            String atributoRemoto = ".";
            switch (r.getTypeEnum()) {
                case OneToMany:
                    OneToManyRelationShip r1 = (OneToManyRelationShip) r;

                    for (ERReference ref : r1.getReferences()) {
                        if (_e == r1.getOneEntity()) {
                            relacionadaCon = ref.getSourceEntity().getName();
                        } else {
                            relacionadaCon = ref.getTargetEntity().getName();
                        }
                        atributoLocal = ref.getSourceAttrib().getName();
                        atributoRemoto = ref.getTargetAttrib().getName();
                        m.addRow(new String[]{relacionadaCon, nombreRelacion, tipoRelacion, atributoLocal, atributoRemoto});
                    }
                    break;
                case OneToOne:
                    //     m.addRow(new String[]{r.getName(),r.getType(),"atributolocal",r.getMembers().get(1).getName(),"atributoremoto",r.getMembers().get(2).getName()});
                    break;
                case ManyToMany:
                    ManyToManyRelationShip r2 = (ManyToManyRelationShip) r;
//                    System.out.println(r2.toVerboseString());
                    for (ERReference ref : r2.getReferences()) {
                        relacionadaCon = ref.getTargetEntity().getName();
                        atributoLocal = ref.getSourceAttrib().getName();
                        atributoRemoto = ref.getTargetAttrib().getName();
                        m.addRow(new String[]{ref.getTargetEntity().getName(), nombreRelacion, tipoRelacion, atributoLocal, atributoRemoto});

                    }


                    break;

            }

        }
    }

    public boolean contains(Iterable<String> col, String key)
    {
      for (Iterator<String> i=col.iterator();i.hasNext();)
      {
          String tmp = i.next();
          if (key.equals(tmp))
              return true;
      }

      return false;
    }

    private void loadAtributesData() {
        Iterable<String>  selec= (Iterable<String>) this._e.getRepresentativeAttibutes();
        
        DefaultListModel listaDisponibles = new DefaultListModel();
        DefaultListModel listaSeleccionados = new DefaultListModel();
        attDisponibles.setModel(listaDisponibles);
        attSelected.setModel(listaSeleccionados);

        for (ERAttrib a:this._e.getAttribs())
        {
            if (contains(selec,a.getName()))
                listaSeleccionados.addElement(a.getName());
            else
                listaDisponibles.addElement(a.getName());
        }
    }

    private void loadComboBox() {
        int size = EREntity.EntityType.values().length;
        String[] tiposStr = new String[size];

        int i=0;
        for (EntityType t:EREntity.EntityType.values())
        {
            tiposStr[i++]=t.toString();
        }
        comboTipo.setModel(new javax.swing.DefaultComboBoxModel(tiposStr));
        comboTipo.setSelectedItem(_e.getErElementType().toString());
    }

    private void loadGeneracionIdentidades() {
        boolean generar=false;
        for (ERAttrib a:this._e.getAttribs())
        {
            if (a.isGenerable())
                generar=true;
        }

        if (!generar){
            this.jCheckBox1.setEnabled(false);
            this.jCheckBox1.setSelected(this._e.isGenerateIdentity());
        }
        else {
          this.jCheckBox1.setEnabled(true);
          this.jCheckBox1.setSelected(this._e.isGenerateIdentity());
        }


    }
}
